package my.mashup.controller;

import my.mashup.Api;
import my.mashup.Result;
import my.mashup.Weight;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static my.mashup.MashupApplication.relMap;
import static my.mashup.MashupApplication.apiMap;

@RestController
public class MainController {
    // 搜索 api
    @GetMapping("/search")
    @ResponseBody
    public Result search(@RequestParam String params) {
        long timeStart = System.currentTimeMillis(); // 计时
        Set<String> keywords = new HashSet<>(Arrays.asList(params.toLowerCase().split(",")));
        long timeEnd = System.currentTimeMillis();
        Result res = searchFunction(keywords);
        res.time = timeEnd - timeStart;
        return res;
    }

    private Result searchFunction(Set<String> cates) {
        Result res = new Result();
        Weight weight = new Weight();
        Set<Api> ans = apiMap.searchMatrix(relMap, cates, weight);
        Set<Api> weightedAns = apiMap.searchWeightedMatrix(relMap, cates, weight);
        res.ans = ans;
        res.weightedAns = weightedAns;
        res.intWeight = weight.intWeight;
        res.doubleWeight = weight.doubleWeight;
        return res;
    }

    // 测试 Mashup 查询结果命中率
    @GetMapping("/test")
    @ResponseBody
    public Map<String, String> test() {
        long timeStart = System.currentTimeMillis(); // 计时
        double hitCount = 0, weightedHitCount = 0, allCount = 0;
        double threshold = 30.0;
        for (String key : relMap.mashupToAddrs.keySet()) {
            Set<String> addrs = relMap.mashupToAddrs.get(key);
            Set<Api> origApis = new HashSet<>();
            Set<String> cates = new HashSet<>();
            for (String addr : addrs) {
                Api temp = relMap.apiByAddr.get(addr);
                if (temp == null) continue;
                cates.add(temp.cate);
                origApis.add(temp);
            }
            Result res = searchFunction(cates);
            if (res.ans.equals(origApis)) {
                hitCount += 1;
            }
            if (res.weightedAns.equals(origApis)) {
                weightedHitCount += 1;
            }
            allCount += 1;
            System.out.println(allCount);
            if (allCount >= threshold) break;
        }
        Map<String, String> ans = new HashMap<>();
        ans.put("rate", String.format("%.2f", hitCount / allCount * 100));
        ans.put("weightedRate", String.format("%.2f", weightedHitCount / allCount * 100));
        long timeEnd = System.currentTimeMillis();
        ans.put("time", String.valueOf(timeEnd - timeStart));
        System.out.println(ans);
        return ans;
    }
}
